package com.ray.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ray.system.table.entity.SysUserRole;
import com.ray.system.table.mapper.SysUserRoleMapper;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.DeleteEnum;
import com.ray.woodencreate.mybatis.DataAuthUtil;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * <p>
 * 用户菜单关联 服务实现类
 * </p>
 *
 * @author shenbo
 * @since 2020-05-28
 */
@Service
public class SysUserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRole> {

    /**
     * 查询用户是否拥有角色
     * @param userCode
     * @param roleCode
     * @return
     */
    public boolean queryUserHasRole(String userCode,String roleCode) {
        SysUserRole query = new SysUserRole();
        query.setUserCode(userCode);
        query.setRoleCode(roleCode);
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>(query);
        DataAuthUtil.notDelete(queryWrapper);
        return ObjectUtil.isNotNull(getOne(queryWrapper));
    }

    /**
     * 编辑角色用户关联
     *
     * @param entity    编辑对象
     * @param loginUser 当前操作员
     * @return
     */
    public boolean delete(SysUserRole entity, LoginUser loginUser) {
        SysUserRole query = new SysUserRole();
        query.setUserCode(entity.getUserCode());
        query.setRoleCode(entity.getRoleCode());
        query.setIsDeleted(DeleteEnum.USE.getValue());
        UpdateWrapper<SysUserRole> updateWrapper = new UpdateWrapper<>(query);
        DataAuthUtil.addDataAuth(updateWrapper, loginUser);
        return update(entity, updateWrapper);
    }

    /**
     * 用户拥有的角色
     * @param userCode
     * @return
     */
    public List<SysUserRole> queryRoleByUserCode(String userCode) {
        SysUserRole query = new SysUserRole();
        query.setUserCode(userCode);
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>(query);
        DataAuthUtil.notDelete(queryWrapper);
        return list(queryWrapper);
    }
}
